package com.liuyun.codec;

import org.apache.commons.codec.digest.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;

/**
 * <p>
 * Copyright: (C), 2021/1/20 23:31
 * <p>
 * <p>
 * Company Information & Data Security Solutions Co., Ltd.
 *
 * @author LiuYun liujw@idss-cn.com
 * @version 1.0
 */
public class CodecDemo {

    public static void main(String[] args) throws NoSuchAlgorithmException {
        // 加密 1亿次
        long count = 100L * 1000L * 1000L;
        byte[] data = "12345".getBytes(StandardCharsets.UTF_8);

        testMult("SHA-256",data,count);
    }


    private static void testMult(String algorithm, byte[] data, long count) throws NoSuchAlgorithmException {
        long startTime = System.nanoTime();
        for (int i = 0; i < count; i++) {
            DigestUtils.sha256(data);
        }
        long nanoTime = System.nanoTime() - startTime;
        final int expectLength = 7;
        if (algorithm.length() < expectLength) {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < expectLength - algorithm.length(); i++) {
                builder.append(" ");
            }

            algorithm += builder.toString();
        }
        System.out.println(algorithm
                + " 加密" + count + "次，耗时：【"
                + " 纳秒=" + nanoTime
                + ", 微秒=" + nanoTime / (1000L)
                + ", 毫秒=" + nanoTime / (1000L * 1000L)
                + ", 秒=" + nanoTime / (1000L * 1000L * 1000L)
                + "】 平均每次耗时" + nanoTime / count + "纳秒");
    }
}
